package com.pinoc.demo;

import com.alibaba.fastjson.JSON;
import com.pinoc.demo.common.es.EsRestHighLevelClient;
import com.pinoc.demo.domain.es.EsUserDocument;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

/**
 * @author yinpeng
 */
public class SearchUtil {

	public static final String index_name = "demo_index_3";

	public static SearchResponse searchById(EsRestHighLevelClient client, String id) throws IOException {
		SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
		searchBuilder.query(QueryBuilders.termQuery("customer_id","id"));
		SearchRequest request = new SearchRequest(index_name).source(searchBuilder);
		SearchResponse search = client.getClient().search(request, RequestOptions.DEFAULT);
		systemOut(search);
		return search;
	}

	public static UpdateResponse updateNameById(EsRestHighLevelClient client, Long id, String name) throws IOException {
		UpdateRequest request = new UpdateRequest(index_name, "50");
		EsUserDocument user = new EsUserDocument();
		user.setId(id);
		user.setName(name);
		request.doc(JSON.toJSONString(user), XContentType.JSON).upsert(JSON.toJSONString(user), XContentType.JSON);
		UpdateResponse update = client.getClient().update(request, RequestOptions.DEFAULT);
		System.out.println(update.toString());
		return update;
	}

	public static UpdateResponse updateAgeById(EsRestHighLevelClient client, Long id, Integer vlaue) throws IOException {
		UpdateRequest request = new UpdateRequest(index_name, id+ "");
		EsUserDocument user = new EsUserDocument();
		user.setId(id);
		user.setAge(vlaue);
		request.doc(JSON.toJSONString(user), XContentType.JSON).upsert(JSON.toJSONString(user), XContentType.JSON);
		return client.getClient().update(request, RequestOptions.DEFAULT);
	}

	public static void systemOut(SearchResponse search) {
		System.out.println("----------------------------------------");
		SearchHit[] hits = search.getHits().getHits();
		for (SearchHit hit : hits) {
			System.out.println(hit.getSourceAsString());
		}
		System.out.println("----------------------------------------");
	}
}
